const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const model = require('./model')
const Chat = model.getModel('chat')

const app = express();
//把socket.io和express绑定
const server = require('http').Server(app);
const io = require('socket.io')(server);

io.on('connection', function(socket) {
	//监听到前端发送信息的事件，拿到数据
	socket.on('sendMsg', function(data){
		console.log(data);
		//然后触发recvMsg事件，把数据广播出去
		const {from, to, msg} = data;
		const chatid = [from, to].sort().join('_');
		Chat.create({chatid, from, to, content: msg}, function(err, doc) {			
			io.emit('recvMsg', Object.assign({}, doc._doc));
		});
	})
})

const userRouter = require('./user')

app.use(cookieParser())
//用来解析post请求的参数
app.use(bodyParser.json())	
//app.use : 使用外部的模块
app.use('/user', userRouter);


server.listen(9093, function () {
	console.log('Node app starts at port 9093')
})

